<?php
class LoginError extends CoreException {
	public function __construct($code)
	{
		$this->library = 'Auth';
		$this->type = 'auth';
		$this->generalError = true;
		$this->code = $code;
		if ($code == 401)
		{
			$this->message = 'User not found.';
		}
		elseif ($code == 402)
		{
			$this->message = 'Password Error.';
		}
	}	
}

class auth {
	protected $hash;
	
	public function __construct()
	{
		$this->hash = new hash();
	}
	
	public function isPosted()
	{
		return isset($_REQUEST['user'], $_REQUEST['pass']);
	}
	
	public function Connect()
	{
		$table = new SQL('user_auth');
		$user = $table->where(
			array(
				'user_login' => $_REQUEST['user'],
			))
			->select();

		if ($user->count() != 1)
		{
			throw new LoginError(401);
		}
		else
		{
			$user = $user->current();
			if (!$this->hash->Check_Hash($_REQUEST['pass'], $user->user_pass))
			{
				throw new LoginError(402);
			}
			else
			{
				return $user->user_id;
			}
		}
	}
	
	public function GetForm ()
	{
		return "<p><label>Utilisateur:<br/><input type=\"text\" name=\"user\" /></label></p>\n
			<p><label>Mot de passe:<br/><input type=\"password\" name=\"pass\" /></label></p>";
	}

	public function ValidLogin($login)
	{
		$table = new SQL('user_auth');
		$user = $table
			->where(array('user_login' => strtolower($login)))
			->select();
		if ($user->count() > 0)
		{
			return 'err_login';
		}
		else
			return true;
	}
	
	public function InscriptionForm ($translate)
	{
		return new form(array(
			array('name' => 'auth_login', 'label' => 'login_field', 'valid' => 'callback', 'callback' => array($this, 'ValidLogin')),
			array('name' => 'auth_pass', 'type' => 'password', 'label' => 'pass_field', 'valid' => 'no_null'),
		), $translate);
	}
	
	public function create($user_id, $vars)
	{
		$table = new SQL('user_auth');
		$table->insert(array(
			'user_id' => $user_id,
			'user_login' => strtolower($vars['auth_login']),
			'user_pass' => $this->hash->hash($vars['auth_pass']),
		));
	}
}